package com.gitee.gateway.dao;

import com.gitee.gateway.beans.DemoBean;
import com.gitee.gateway.core.cache.Cache;
import com.gitee.gateway.core.cache.CacheEvict;
import org.jdbi.v3.sqlobject.config.RegisterRowMapper;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;

import java.util.List;

public interface DemoDao {

    String REGION = "Demo";

    @SqlQuery("SELECT * FROM demos WHERE id=:id")
    @RegisterRowMapper(DemoBean.class)
    @Cache(region = REGION, key = ":id")
    DemoBean read(@Bind("id") long id);

    @SqlUpdate("INSERT INTO demos(`name`,`age`) VALUES(:name,:age)")
    @GetGeneratedKeys
    @CacheEvict(region = REGION, key = ":id", key2 = "all", key3 = "count")
    int insert(@BindBean DemoBean demo);

    @SqlUpdate("UPDATE demos SET age=:age,name=:name WHERE id=:id")
    @CacheEvict(region = REGION, key = ":id", key2 = "all")
    int update(@BindBean DemoBean demo);

    @SqlUpdate("DELETE FROM demos WHERE id=:id")
    @CacheEvict(region = REGION, key = ":id", key2 = "all", key3 = "count")
    int delete(@Bind("id") long id);

    @SqlQuery("SELECT * FROM demos ORDER BY id DESC")
    @RegisterRowMapper(DemoBean.class)
    @Cache(region = REGION, key = "all")
    List<DemoBean> list();

    @SqlQuery("SELECT COUNT(*) FROM demos")
    @Cache(region = REGION, key = "count")
    int count();

    default List<DemoBean> filterByAge(int age) {
        return list().stream().filter(demo -> demo.getAge() == age).toList();
    }

}
